package cn.knight.system.service.impl;

import cn.knight.basic.query.BaseQuery;
import cn.knight.basic.utils.PageList;
import cn.knight.system.domain.Menu;
import cn.knight.system.domain.Permission;
import cn.knight.system.domain.Role;
import cn.knight.system.mapper.MenuMapper;
import cn.knight.system.mapper.PermissionMapper;
import cn.knight.system.mapper.RoleMapper;
import cn.knight.system.service.IRoleService;
import cn.knight.basic.service.impl.BaseServiceImpl;

import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author winnie
 * @since 2022-07-13
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {

    @Autowired
    private  RoleMapper roleMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public PageList<Role> queryRows(BaseQuery baseQuery) {
        List<Role> roles = roleMapper.queryRows(baseQuery);
        for (Role role : roles) {
            role.setOwnMenus(menuMapper.loadByRoleId(role.getId()));
            role.setOwnPermissions(permissionMapper.loadByRoleId(role.getId()));

        }
        Integer count = roleMapper.queryCount(baseQuery);

        return new PageList<>(count, roles);
    }

    @Override
    public void save(Role role) {
        roleMapper.save(role);
        initsaveRelationTable(role);
    }

    private void initsaveRelationTable(Role role) {
        if (role.getMenus() != null){
            // 根据角色表的id和菜单&权限的数组添加数据到中间表中
            roleMapper.saveRoleMenu(role.getId(),role.getMenus());
            roleMapper.saveRolepermission(role.getId(),role.getPermissions());
        }
    }

    @Override
    public void update(Role role) {
        // 修改角色表数据
        roleMapper.update(role);
        // 修改中间表的数据
        initRelationTable(role);
    }

    private void initRelationTable(Role role) {
        if (role.getMenus() != null) {
            // 根据角色表删除菜单&权限中间表中的对应数据
            roleMapper.removeRoleMenu(role.getId());
            roleMapper.removeRolepermission(role.getId());

            // 根据角色表的id和菜单&权限的数组添加数据到中间表中
            roleMapper.saveRoleMenu(role.getId(), role.getMenus());
            roleMapper.saveRolepermission(role.getId(), role.getPermissions());
        }

    }

    @Override
    public void remove(Long id) {
        roleMapper.remove(id);
        initDelRelationTable(id);
    }

    private void initDelRelationTable(Long id) {
        // 根据角色表删除菜单&权限中间表中的对应数据
        roleMapper.removeRoleMenu(id);
        roleMapper.removeRolepermission(id);
    }
}
